<template>
  <div class="roles">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row class="addRoles">
        <el-col>
          <el-button type="primary" @click="addroles">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleslist" border style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
              class="borderBottom vcenter"
              :class="{borderTop:index1 == 0}"
            >
              <el-col :span="6">
                <el-tag closable @close="handleClose(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <span class="el-icon-caret-right"></span>
              </el-col>
              <el-col :span="18">
                <el-row
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                  :class="{borderTop:index2 !== 0}"
                  class="vcenter"
                >
                  <el-col :span="9">
                    <el-tag
                      type="success"
                      closable
                      @close="handleClose(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <span class="el-icon-caret-right"></span>
                  </el-col>
                  <el-col :span="15">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="handleClose(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="360px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editroles(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteroles(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="Assignpermissions(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="添加角色" :visible.sync="addVisible" width="60%" @close="addreset">
      <el-form :model="addForm" :rules="addrules" ref="addFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolestrue">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改角色" :visible.sync="modifyVisible" width="60%" @close="modifyreset">
      <el-form :model="modifyForm" :rules="modifyrules" ref="modifyFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="modifyForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="modifyForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyVisible = false">取 消</el-button>
        <el-button type="primary" @click="modifyRolestrue">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配权限" :visible.sync="AssignPermissionsVisible" width="60%" @close="emptyDefaultCheckedKeys()">
      <el-tree ref="treeRefs" show-checkbox default-expand-all :data="treeData" :props="defaultProps" node-key="id" :default-checked-keys="defaultCheckedKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AssignPermissionsVisible = false">取 消</el-button>
        <el-button type="primary" @click="AssignPermissionstrue">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "roles",
  data() {
    return {
      roleslist: [],
      addVisible: false,
      modifyVisible: false,
      AssignPermissionsVisible: false,
      addForm: {},
      modifyForm: {},
      modifyrules: {
        roleName: [{ required: true, message: "请输入角色", trigger: "blur" }]
      },
      addrules: {
        roleName: [{ required: true, message: "请输入角色", trigger: "blur" }]
      },
      treeData: [],
      defaultProps: {
        label: "authName",
        children: "children"
      },
      defaultCheckedKeys:[],
      roleId:""
    };
  },
  methods: {
    getlist() {
      this.$http.get("roles").then(res => {
        this.roleslist = res.data.data;
        console.log(this.roleslist);
      });
    },
    addroles() {
      this.addVisible = true;
    },
    addRolestrue() {
      this.$refs.addFormRef.validate(validate => {
        if (validate) {
          this.$http.post("roles", this.addForm).then(res => {
            this.$message.success("添加角色成功");
            this.addVisible = false;
            this.getlist();
          });
        } else {
          this.$message.error("格式错误");
        }
      });
    },
    addreset() {
      this.$refs.addFormRef.resetFields();
    },
    modifyreset() {
      this.$refs.modifyFormRef.resetFields();
    },
    editroles(Id) {
      this.modifyVisible = true;
      this.$http.get(`roles/${Id}`).then(res => {
        this.modifyForm = res.data.data;
        console.log(res.data.data);
      });
    },
    modifyRolestrue() {
      this.$refs.modifyFormRef.validate(validate => {
        if (validate) {
          this.$http
            .put("roles/" + this.modifyForm.roleId, {
              roleName: this.modifyForm.roleName,
              roleDesc: this.modifyForm.roleDesc
            })
            .then(res => {
              this.modifyVisible = false;
              this.getlist();
              this.$message.success("修改角色成功");
              console.log(res);
            });
        } else {
          this.$message.error("格式错误");
        }
      });
    },
    deleteroles(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http.delete("roles/" + id).then(res => {
            if (res.data.meta.status !== 200) {
              return this.$message({
                type: "error",
                message: "删除失败"
              });
            }
            this.getlist();
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    Assignpermissions(node) {
      this.roleId =node.id;
      this.$http.get("rights/tree").then(res => {
        this.treeData = res.data.data;
        console.log(this.treeData);
      });
      this.getArray(node,this.defaultCheckedKeys);
      this.AssignPermissionsVisible = true;
    },
    AssignPermissionstrue() {
      let allKeys=[];
      allKeys =[...this.$refs.treeRefs.getCheckedKeys(),...this.$refs.treeRefs.getHalfCheckedKeys()];
      //console.log(allKeys)
      this.$http.post(`roles/${this.roleId}/rights`,{rids:allKeys.join(",")}).then( res => {
        console.log(res);
        if(res.data.meta.status !== 200){
          this.$message.error("角色授权失败");
        }
        this.$message.success("角色授权成功");
        this.getlist();
      })
      this.AssignPermissionsVisible =false;
    },
    getArray(node,arr) {
      if(!node.children){
        return arr.push(node.id);
      }
      node.children.forEach(element => {
        this.getArray(element,arr);
      });

    },
    handleClose(role, rightId) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http.delete(`roles/${role.id}/rights/${rightId}`).then(res => {
            if (res.data.meta.status !== 200) {
              return this.$message.error("失败");
            }
            this.$message.success("删除成功");
            role.children = res.data.data;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    emptyDefaultCheckedKeys() {
      this.defaultCheckedKeys = []
    }
  },
  mounted() {
    this.getlist();
  }
};
</script>

<style scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}
.addRoles {
  margin-bottom: 15px;
}
.el-tag {
  margin: 5px;
}
.borderTop {
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.borderBottom {
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
